<?php

namespace app\api\controller\balance;

use app\api\controller\Controller;
use app\api\model\settings\Setting as SettingModel;
use app\common\enum\user\UserCashPayTypeEnum;
use app\common\enum\user\UserCashStatusEnum;
use app\common\model\user\UserCash;
use app\common\service\cash\CashService;

/**
 * 提现
 */
class Withdraw extends Controller
{
    /**
     * 提现设置
     */
    public function setting()
    {
        // 提现设置
        $setting = SettingModel::getItem('balance_cash');
        return $this->renderSuccess('', $setting);
    }

    //申请提现
    public function apply()
    {
        $user = $this->getUser();
        if (!$user) {
            return $this->renderError('用户未登录');
        }
        $param = $this->postData();
        $able = CashService::ableWithdraw($user, $param);
        if (!$able['status']) {
            return $this->renderError($able['msg']);
        }
        $user->startTrans();
        try {
            $setting = SettingModel::getItem('balance_cash');
            $deduct = $setting['deduct'];
            $cash_broke = round($param['money'] * $deduct/100,2);
            $real_money = $param['money']-$cash_broke;
            //添加提现申请记录
            $row = UserCash::create([
                'user_id' => $user['user_id'],
                'money' => $param['money'],
                'pay_type' => $param['pay_type'] ?? UserCashPayTypeEnum::WX,
                'apply_status' => UserCashStatusEnum::WAIT,
                'app_id' => $user['app_id'],
                'cash_broke'=>$cash_broke,
                'real_money'=>$real_money,
            ]);
            if (!$row) {
                $user->rollback();
                return $this->renderError('提现申请失败');
            }
            //扣除余额，增加冻结金额
            $user->balance -= $param['money'];
            $user->freeze_money += $param['money'];
            $user->save();
            $user->commit();
            return $this->renderSuccess('提现申请成功');
        } catch (\Exception $e) {
            $user->rollback();
            return $this->renderError($e->getMessage());
        }
    }

    //提现记录
    public function logs()
    {
        $user = $this->getUser();
        if (!$user) {
            return $this->renderError('用户未登录');
        }
        $param = $this->postData();
        $page = $param['page'] ?? 1;
        $pageSize = $param['pageSize'] ?? 10;
        $apply_time = $param['apply_time'] ?? [];
        $status = $param['status'] ?? 0;
        $map = [
            ['user_id', '=', $user['user_id']],
        ];
        if ($status) {
            $map[] = ['apply_status', '=', $status];
        }
        $model = UserCash::where($map);
        if ($apply_time) {
            $model->whereBetweenTime('apply_time', $apply_time[0], $apply_time[1]);
        }
        $lists = $model->order('id desc')->paginate($pageSize);
        return $this->renderSuccess('', compact('lists'));
    }
}